package dbs

import (
	"github.com/jinzhu/gorm"
	"github.com/spf13/cast"
	"strconv"
	"time"
)

type DbConfig struct {
	ID           uint      `json:"id" gorm:"primary_key"`
	Key          string    `json:"key" gorm:"type:varchar(64);not null;unique"`                //key
	Name         string    `json:"name" gorm:"type:varchar(255)"`                              //名称
	Value        string    `json:"value" gorm:"type:varchar(255)"`                             //值
	ValueExplain string    `json:"value_explain" gorm:"type:varchar(255);not null;default:''"` //值说明
	Hide         bool      `json:"hide" gorm:"type:bool;default:false"`                        //true 页面不展示
	CreatedBy    string    `json:"created_by" gorm:"type:varchar(64)"`                         // 创建人
	UpdateBy     string    `json:"update_by" gorm:"type:varchar(64)"`                          // 最近更改的人
	CreatedAt    time.Time `json:"created_at" gorm:"type:datetime"`
	UpdatedAt    time.Time `json:"updated_at" gorm:"type:datetime"`
	FormType     string    `json:"form_type" gorm:"type:varchar(32)"`
}

type ConfigCreate struct {
	Name         string `json:"name" validate:"required" label:"名称"`
	Key          string `json:"key" validate:"required" label:"键名称"`
	Value        string `json:"value"`
	ValueExplain string `json:"value_explain"`
	Hide         bool   `json:"hide"`
	FormType     string `json:"form_type"`
}

type ConfigUpdate struct {
	ID           uint   `json:"id" validate:"required"`
	Name         string `json:"name" validate:"required" label:"名称"`
	Value        string `json:"value" validate:"required"`
	ValueExplain string `json:"value_explain"`
	Hide         bool   `json:"hide"`
	FormType     string `json:"form_type"`
}

type ConfigList struct {
	ID        int
	Name      string
	Key       string
	Hide      bool
	WhereHide bool
}

func (c *DbConfig) Create() (err error) {
	err = D_Pool(func(db **gorm.DB) (err error) {
		conn := *db

		return conn.Create(&c).Error
	})
	return
}

func (c *DbConfig) Exit() (err error) {
	err = D_Pool(func(db **gorm.DB) (err error) {
		conn := *db

		if c.Key != "" {
			conn = conn.Where("`key` = ?", c.Key)
		}

		err = conn.Select("id").First(&c).Error
		return
	})
	return
}

func (c *DbConfig) Get() (err error) {
	err = D_Pool(func(db **gorm.DB) (err error) {
		conn := *db
		if c.Key != "" {
			conn = conn.Where("`key` = ?", c.Key)
		}
		return conn.First(&c).Error
	})
	return
}

func (c *DbConfig) GetList(req ConfigList) (data []DbConfig, err error) {
	err = D_Pool(func(db **gorm.DB) (err error) {
		conn := *db
		if req.Key != "" {
			conn = conn.Where("`key` like ?", "%"+req.Key+"%")
		}
		if req.Name != "" {
			conn = conn.Where("`name` like ?", "%"+req.Name+"%")
		}
		if req.WhereHide {
			conn = conn.Where("hide = ?", req.Hide)
		}
		if req.ID > 0 {
			conn = conn.Where("id = ?", req.ID)
		}
		return conn.Find(&data).Error
	})
	return
}

func (c *DbConfig) Update(params map[string]interface{}) (err error) {
	err = D_Pool(func(db **gorm.DB) (err error) {
		conn := *db

		return conn.Model(&c).Update(params).Error
	})
	return
}

func (c *DbConfig) Format() (result map[string]interface{}) {
	//todo last time
	// 格式化用户返回值
	result = map[string]interface{}{
		"id":            c.ID,
		"key":           c.Key,
		"name":          c.Name,
		"value":         c.Value,
		"value_explain": c.ValueExplain,
		"hide":          c.Hide,
		"created_by":    c.CreatedBy,
		"update_by":     c.UpdateBy,
		"created_at":    c.CreatedAt.Format("2006-01-02 15:04:05"),
		"update_at":     c.UpdatedAt.Format("2006-01-02 15:04:05"),
		"form_type":     c.FormType,
	}
	return
}

func GetConfigByApprovalPassPeriod(s string) (day int) {
	var config DbConfig
	config.Key = "approval_pass_period_" + s
	if err := config.Get(); err != nil {
		return 30
	}
	day, _ = strconv.Atoi(config.Value)
	if day < 1 {
		return 30
	}
	return day
}

func GetConfigByPhotoIssuedMachine() (b bool) {
	var config DbConfig
	config.Key = "photo_issued_machine"
	if err := config.Get(); err != nil {
		return false
	}
	parseBool, err := strconv.ParseBool(config.Value)
	if err != nil {
		return false
	}
	return parseBool
}

func GetApprovalPassPatientLeave() (b int) {
	var config DbConfig
	config.Key = "approval_pass_patient_leave"
	if err := config.Get(); err != nil {
		return 0
	}
	return cast.ToInt(config.Value)
}
